/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
// 这是 ai 的回答，我觉得 ai 的回答的比较好
var merge = function (intervals) {
  if (intervals.length === 0) return [];

  // 按区间的起始点升序排序
  intervals.sort((a, b) => a[0] - b[0]);

  const merged = [intervals[0]]; // 初始化结果数组

  for (let i = 1; i < intervals.length; i++) {
    const current = intervals[i];
    const lastMerged = merged[merged.length - 1];

    // 如果当前区间与最后一个合并区间重叠，则合并
    if (current[0] <= lastMerged[1]) {
      // 更新最后一个合并区间的结束点为较大值
      lastMerged[1] = Math.max(lastMerged[1], current[1]);
    } else {
      // 不重叠，直接添加当前区间
      merged.push(current);
    }
  }

  return merged;
};
/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
var merge = function (intervals) {
  if (intervals.length <= 1) return intervals;
  let resultArr = [];
  intervals.sort((a, b) => a[0] - b[0]);
  resultArr.push(intervals[0]);
  for (let i = 1; i < intervals.length; i++) {
    if (intervals[i][0] > resultArr[resultArr.length - 1][1]) {
      resultArr.push(intervals[i]);
    } else {
      resultArr[resultArr.length - 1][1] = Math.max(
        intervals[i][1],
        resultArr[resultArr.length - 1][1]
      );
    }
  }
  return resultArr;
};

let arr = [
  [1, 2],
  [0, 2],
  [4, 5],
  [3, 5],
];
merge(arr).forEach((item) => console.log(item));
// console.log(merge(arr));
